<template>
  <div class="main">
    <div class="left">
      <div
        class="content"
        v-for="(item, index) in list"
        :key="index"
        @click="subitem(index, item.userId)"
        :class="UserIndex == index ? 'back' : ''"
        v-if="list.length > 0"
      >
        <div class="content-left">
          <div class="lefts">
            <div style="position: relative">
              <img class="imgs" :src="$staticURL + item.headimgUrl" />
            </div>
          </div>
          <div class="rights">
            <div
              class="rights_button"
              style="padding-bottom: 30px; font-weight: 600"
            >
              {{ item.nickName }}
            </div>
            <div>{{ item.lastMes.mesContent }}</div>
          </div>
        </div>

        <div class="content-right">
          <div style="padding-bottom: 30px">{{ item.lastMesTime }}</div>
          <!-- <el-button class="city" @click="removeUserFromMessageList(item)">删除</el-button> -->
          <el-badge
            v-if="!show&&item.unReadNum"
            :value="item.unReadNum"
            :max="99"
            style="padding-top: 10px"
          />
        </div>
      </div>
      <!-- <button @click="playSound()">1111111</button> -->
    </div>
    <div class="right" v-show="show" ref="mianscroll">
      <div class="chat-content" id="mianscroll">
        <!-- recordContent 聊天记录数组-->
        <div
          v-for="(itemc, indexc) in recordContent"
          :key="indexc"
          v-if="recordContent.length > 0"
        >
          <!-- 对方 -->
          <div class="word" v-if="itemc.userId == uid">
            <img :src="$staticURL + itemc.headimgUrl" />
            <div class="info">
              <p class="time">{{ itemc.nickName }} {{ itemc.sendTime }}</p>
              <div class="info-content" v-if="itemc.contentType == 1||itemc.contentType == 4">
                  {{ itemc.mesContent }}
                </div>
                <div class="info-content" v-if="itemc.contentType == 2">
                  <img
                    v-if="itemc.mesContent"
                    :src="$staticURL + itemc.mesContent"
                  />
                </div>
                <div class="info-content" v-if="itemc.contentType == 3&&itemc.mesContent">
                  <video :src="$staticURL +itemc.mesContent"></video>
                </div>
            </div>
          </div>
          <!-- 我的 -->
          <div class="word-my" v-if="itemc.userId == kfUser.userId">
            <div style="display: flex; align-items: center">
              <div class="info" v-if="itemc.mesContent">
                <p class="time">{{ itemc.nickName }} {{ itemc.sendTime }}</p>
                <div class="info-content" v-if="itemc.contentType == 1||itemc.contentType == 4">
                  {{ itemc.mesContent }}
                </div>
                <div class="info-content" v-if="itemc.contentType == 2">
                  <img
                    v-if="itemc.mesContent"
                    :src="$staticURL + itemc.mesContent"
                  />
                </div>
                <div class="info-content" v-if="itemc.contentType == 3">
                  <video :src="$staticURL +itemc.mesContent"></video>
                </div>
              </div>
              <div>
                <img :src="$staticURL + itemc.headimgUrl" />
              </div>
            </div>
          </div>
        </div>
        <div style="height: 10px" class="position-box"></div>
      </div>
      <div class="chat">
        <div class="clat_btn">
          <el-upload
            class="upload-demo"
            accept="image/jpeg,image/gif,image/png"
            action="https://api.yushiai.com.cn/biz/uploadImgage"
            :headers="headers"
            :on-preview="handlePreview"
            :on-success="upSuccess"
            multiple
            :limit="1"
            name="image"
          >
            <el-button size="small" type="primary">点击上传图片</el-button>
          </el-upload>
          <el-button type="success" class="del1" @click="sendMessage()"
            >发送</el-button
          >
          <el-button type="danger" class="del" @click="Cinfo()"
            >结束对话</el-button
          >
        </div>
        <el-input
          class="chat_qq"
          type="textarea"
          :rows="12"
          placeholder="请输入内容"
          @keyup.enter.native="sendMessage()"
          v-model="textarea"
        >
        </el-input>
      </div>
    </div>
    <!-- <div v-show="show" class="keyword" ref="mianscroll1">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>常用语</span>
        </div>
        <div v-for="o in 4" :key="o" class="text item">
          {{ "列表内容 " + o }}
        </div>
      </el-card>
    </div> -->
  </div>
</template>

<script>
let ws = null;
let setIntervalWesocketPush = null;
import { getToken } from "@/utils/auth";
// import { createSocket } from '@/utils/websocket'
export default {
  name: "Message",

  data() {
    return {
      mesContent: '',
      uid: "",
      fileList: [],
      color: "",
      show: false,
      textarea: "",
      UserIndex: 0,
      // 心跳传输给后端
      ws: "ACT:heart_beat",
      // 用户数据
      list: [
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "2csdfa",
          time: "das",
          m: "6",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "2csdfa",
          time: "das",
          m: "6",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "2csdfa",
          time: "das",
          m: "6",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "2csdfa",
          time: "das",
          m: "6",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "2csdfa",
          time: "das",
          m: "6",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "55555555555555555555555555555555555555555555555555555555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "22255",
          time: "555",
          m: "6666",
        },
        {
          Image:
            "https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0",
          name: "222",
          time: "555",
          m: "6666",
        },
      ],
      // 聊天数据
      recordContent: [
        {
          mineMsg: "1",
          nickName: "123",
          timestamp: "111",
          contactText: "1111",
        },
        {
          mineMsg: "0",
          nickName: "123",
          timestamp: "111",
          contactText: "1111",
        },
        {
          mineMsg: "1",
          nickName: "123",
          timestamp: "111",
          contactText: "1111",
        },
        {
          mineMsg: "0",
          nickName: "123",
          timestamp: "111",
          contactText: "1111",
        },
        {
          mineMsg: "1",
          nickName: "123",
          timestamp: "111",
          contactText: "1111",
        },
        {
          mineMsg: "0",
          nickName: "123",
          timestamp: "111",
          contactText: "1111",
        },
        {
          mineMsg: "1",
          nickName: "123",
          timestamp: "111",
          contactText: "1111",
        },
        {
          mineMsg: "0",
          nickName: "123",
          timestamp: "111",
          contactText: "1111",
        },
        {
          mineMsg: "1",
          nickName: "123",
          timestamp: "111",
          contactText: "1111",
        },
        {
          mineMsg: "0",
          nickName: "123",
          timestamp: "111",
          contactText: "1111",
        },
      ],
      path: "wss://api.yushiai.com.cn/websocket",
      socket: "",
      timeout: 28 * 1000, //30秒一次心跳
      timeoutObj: null, //心跳心跳倒计时
      serverTimeoutObj: null, //心跳倒计时
      timeoutnum: null, //断开 重连倒计时
      kfUser: "",
      // ct: 1,
      client: "",
      // sound: require('@/assets/audio/web.wav'),
      sound: require("@/assets/audio/WeChatRed.mp3"),
    };
  },

  computed: {
    headers() {
      return {
        session_token: getToken(),
      };
    },
  },
  // watch:{
  //   open(newVal,oldVal) {
  //     console.log('新的:', newVal);
  //     console.log('旧的:', oldVal);
  //   }
  // },
  mounted() {
    // this.getCustomerServiceMessageList()
    this.getCustomerServiceReplyList();
    // this.init();
    this.getUserMessage();
    // createSocket(this.path)

    // if (this.client) {
    //   // this.client.end()
    // } else {
    this.MQTTINIT();
    // }
  },

  methods: {
    async removeUserFromMessageList(item){
     let res=await  this.$API.kefu.removeUserFromMessageList({userId:item})
     if( res.code==200){
      console.log('uuuu');
       this.getCustomerServiceReplyList()
     }
    },
    // addQuickPhrases() {
    //   this.$API.kefu.addQuickPhrases();
    // },
    playSound() {
      let sound = new Audio(this.sound);
      sound.play();
    },
    MQTTINIT() {
      let options = {
        username: "w_mqtt01",
        clientId: "mqtt_" + Math.random().toString(16).substr(2, 8),
        connectTimeout: 600000,
        keepalive: 60, // 心跳，单位秒，如果后台开启监听可以快速知道有没有退出
        clean: true,
        password: "Wt1107@ok!",
        // reconnectPeriod: 5000,
      };
      // 订阅 topic。如果订阅多个 var subscribe = ["test1","test2"]
      var subscribe = "ysa_" + localStorage.getItem("id");

      if (this.client) {
        this.client.end();
      }
      // ws://47.94.158.177:20083/mqtt
      // wx://47.94.158.177:20083/mqtt
      // mqtt://47.94.158.177:1008
      // this.client = this.$MQTT.connect('wss://47.94.158.177:30083/mqtt', options)
      this.client = this.$MQTT.connect(
        "wss://wss.yushiai.com.cn:30083/mgtt",
        options
      );
      this.client
        .on("connect", (res) => {
          console.log(res, "连接成功");
          this.client.subscribe(subscribe, (err) => {
            // console.log(err, 2222);
            if (!err) {
              console.log(err, "订阅成功");
            }
          });
        })
        .on("message", (topic, message) => {
          this.playSound();
          this.getCustomerServiceReplyList();
          console.log("消息接收", topic, message);
          const data = JSON.parse(message.toString());
          console.log("收到服务器内容转换对象：", data);
          let obj = data.msgContent;
          if (obj.ContentType == 1) {
            this.recordContent = [
              ...this.recordContent,
              {
                headimgUrl: obj.HeadimgUrl || "",
                mesContent: obj.MesContent || "",
                sendTime: obj.SendHour + ":" + obj.SendMinute,
                contentType: obj.ContentType,
                // type: newVal.MesType || '',
                userId: obj.FromUserId,
                nickName: obj.NickName,
              },
            ];
          } else if (obj.ContentType == 2) {
            this.recordContent = [
              ...this.recordContent,
              {
                headimgUrl: obj.HeadimgUrl || "",
                mesContent: obj.MesContent || "",
                sendTime: obj.SendHour + ":" + obj.SendMinute,
                userId: obj.FromUserId,
                contentType: obj.ContentType,
                nickName: obj.NickName,
              },
            ];
          }

          this.bottomScrollClick();
        })
        .on("reconnect", (topic, message) => {
          console.log("重连");
        })
        .on("error", (res) => {
          console.log(res);
          //重新连接
          client.reconnect();
        });
      // close： function () {} 断开连接回调
      // offline ： function () {} 客户端离线回调
      // 发送，
      // this.client.publish('system','hello',{},(res)=>{
      // 		console.log(res)
      // })
      //  system: topic订阅的主题,第二个参数发送内容Buffer or String类型(可以转成JSON字符串JSON.stringify()),第三个参数[options]看下方【不必填】,第四个回调【不必填】
      // 	qos QoS 等级, Number, default 0
      //	retain 保留消息标志, Boolean, default false
      //	dup 重复标志, Boolean, default false
    },
    // 及时通讯WebSocket
    init() {
      // if (typeof(WebSocket) === "undefined") {
      //   alert("您的浏览器不支持socket")
      // } else {
      //   // 实例化socket
      //   this.socket = new WebSocket(this.path)
      //   // 监听socket连接
      //   this.socket.onopen = this.open
      //   // 监听socket错误信息
      //   this.socket.onerror = this.error
      //   // 监听socket消息
      //   this.socket.onmessage = this.getMessage
      // }
    },
    // destroyed() {
    //     // 销毁监听
    //     this.socket.onclose = this.close
    // },
    open: function (commit) {
      console.log("socket连接成功");
      let userId = localStorage.getItem("id");
      // this.start()
      console.log(userId, "取本地的id");
      // console.log();
      console.log("webSocket状态:318", commit.currentTarget.readyState);
      if (commit.currentTarget.readyState == 1) {
        this.send(`ACT:login_user;UserId:${userId}`);
      } else {
        this.init();
      }
    },
    error: function () {
      console.log("连接错误");
      this.init();
    },
    getMessage: function (msg) {
      console.log(msg, "消息");
      console.log(msg.data, "消息");
      // this.reset();
      var res = msg;
      console.log("收到服务器内容：", res);
      let arr = res.data.split(";");
      let obj = {};

      for (var i = 0; i < arr.length; i++) {
        // 把每一项再按照=拆分 得到左边的当成对象key 右边当成对象value
        let sonArr = arr[i].split(":");
        obj[sonArr[0]] = sonArr[1];
      }
      console.log("收到服务器内容转换对象：", obj);
      this.bottomScrollClick();
      if (obj.ContentType == 1) {
        this.recordContent = [
          ...this.recordContent,
          {
            headimgUrl: obj.HeadimgUrl || "",
            mesContent: obj.MesContent || "",
            sendTime: obj.SendHour + ":" + obj.SendMinute,
            contentType: obj.ContentType,
            // type: newVal.MesType || '',
            userId: obj.FromUserId,
            nickName: obj.NickName,
          },
        ];
      } else if (obj.ContentType == 2) {
        this.recordContent = [
          ...this.recordContent,
          {
            headimgUrl: obj.HeadimgUrl || "",
            mesContent: obj.MesContent || "",
            sendTime: obj.SendHour + ":" + obj.SendMinute,
            userId: obj.FromUserId,
            contentType: obj.ContentType,
            nickName: obj.NickName,
          },
        ];
      }
      console.log(this.recordContent);
      this.$forceUpdate();
    },
    send: function (user) {
      console.log("开始发送" + user);
      // 传输给后端续心跳
      // this.socket.send(this.ws)
      this.socket.send(this.ws);
      this.socket.send(user);
    },
    close: function () {
      console.log("socket已经关闭");
      clearInterval(setIntervalWesocketPush);
      // this.reconnect();
    },
    // //开启心跳
    // start(){
    //     var self = this;
    //     self.timeoutObj && clearTimeout(self.timeoutObj);
    //     self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
    //     self.timeoutObj = setTimeout(function(){
    //         //这里发送一个心跳，后端收到后，返回一个心跳消息，
    //         if (self.init.currentTarget.readyState == 1) {//如果连接正常
    //             self.socket.send();

    //         }else{//否则重连
    //             self.socket.onopen();
    //         }
    //         self.serverTimeoutObj = setTimeout(function() {
    //             //超时关闭
    //             self.socket.close();
    //         }, self.timeout);

    //     }, self.timeout)
    // },

    // reset(){//重置心跳
    //     var that = this;
    //     //清除时间
    //     clearTimeout(that.timeoutObj);
    //     clearTimeout(that.serverTimeoutObj);
    //     //重启心跳
    //     that.start();
    // },

    // // 获取所有聊天列表
    // async getCustomerServiceMessageList() {
    //     let res = await this.$API.kefu.getCustomerServiceMessageList()
    //     console.log(res, "212  获取所有聊天列表")
    //     // this.list = res.data;
    // },

    bottomScrollClick() {
      // document.getElementsByClassName('position-box')[0].scrollIntoView();
      // this.$nextTick 将回调延迟到下次DOM更新循环之后执行。在修改数据之后立即使用它，然后等待DOM更新
      this.$nextTick(() => {
        // dom 元素更新后执行滚动条到底部 否则不生效
        let scrollElem = this.$refs.mianscroll.getBoundingClientRect().height;

        // scrollElem.scrollTop = scrollElem.scrollHeight
        scrollElem.scrollTop({
          top: scrollElem.scrollHeight,
          behavior: "smooth",
        });
      });
    },
    // 获取消息列表
    async getCustomerServiceReplyList() {
      let res = await this.$API.kefu.getCustomerServiceReplyList();
      console.log(res, "217   获取消息列表");
      this.list = res.data;
    },

    async getUserMessage() {
      let res = await this.$API.kefu.getUserMessage();
      console.log(res, "217   获取客服信息");
      this.kfUser = res.data;
      console.log(this.kfUser, "217   this.kfUser");
    },

    // 获取用户id消息列表
    async getCustomerServiceReplyMessageListById(userId) {
      let res = await this.$API.kefu.getCustomerServiceReplyMessageListById({
        userId,
      });
      console.log(res, "217   获取用户id消息列表");
      this.recordContent = res.data;
      this.getCustomerServiceReplyList()
    },

    // 发送客服信息
    async sendCustomerServiceMessage(data) {
      let res = await this.$API.kefu.sendCustomerServiceMessage(data);
      console.log(res, "发送客服信息");
      this.textarea = "";
      // this.recordContent = res.data;
      this.bottomScrollClick();
    },

    // 结束客服聊天
    async endCustomerServiceByUserId() {
      console.log(0);
      let res = await this.$API.kefu.endCustomerServiceByUserId({
        userId: this.uid,
      });
      console.log(res, "217 结束客服聊天");
      clearInterval(setIntervalWesocketPush);
    },
    formatTime(time, fmt) {
      if (!time) return "";
      else {
        const date = new Date(time);
        const o = {
          "M+": date.getMonth() + 1,
          "d+": date.getDate(),
          "H+": date.getHours(),
          "m+": date.getMinutes(),
          "s+": date.getSeconds(),
          "q+": Math.floor((date.getMonth() + 3) / 3),
          S: date.getMilliseconds(),
        };
        if (/(y+)/.test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            (date.getFullYear() + "").substr(4 - RegExp.$1.length)
          );
        for (const k in o) {
          if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length === 1
                ? o[k]
                : ("00" + o[k]).substr(("" + o[k]).length)
            );
          }
        }
        return fmt;
      }
    },
    // 发送
    sendMessage(ct) {
      console.log("点击发送按钮");
      if (this.textarea == "") {
        uni.showToast({
          title: "请先输入内容",
          icon: "none",
          duration: 2000,
        });
        return false;
      }
      let item = {
        headimgUrl: this.kfUser.headimgurl,
        nickName: this.kfUser.userName,
        mesContent: this.textarea,
        sendTime: this.formatTime(new Date(), "HH:mm"),
        // type: 1,
        contentType: ct || 1,
        userId: this.kfUser.userId,
      };
      this.recordContent = [...this.recordContent, item];
      console.log(this.recordContent);

      var info = {
        mesContent: this.textarea,
        toUser: this.uid,
        contentType: ct || 1,
      };
      this.sendCustomerServiceMessage(info);
    },
    // 打开聊天
    subitem(index, id) {
      // if(this.uid){
      //    this.endCustomerServiceByUserId()
      // }
      
      this.uid = id;
      this.UserIndex = index;
      this.show = true;
      // this.init()
      this.getCustomerServiceReplyMessageListById(id);
      // clearInterval(setIntervalWesocketPush)
      // setIntervalWesocketPush = setInterval(() => {
      //   // this.socket.send(this.ws)
      //   // this.socket.send(user)
      //   this.init()
      // }, 30000)
      // if(this.show){
      //   ;
      // }
      setTimeout(() => {
        this.bottomScrollClick();
      }, 500);
    },
    // 关闭聊天
    Cinfo(item) {
      this.show = !this.show;
      this.close();
     
      this.removeUserFromMessageList(this.uid);
      this.endCustomerServiceByUserId(this.uid);
      this.getCustomerServiceReplyList()
    },
    upSuccess(response) {
      console.log(response.data.imgageUrl);
      this.textarea = response.data.imgageUrl;
      // this.ct = 2
      this.sendMessage(2);
    },
    // // Elmer文件上传钩子函数
    handleRemove() {},
    handlePreview(file) {
      console.log(file);
    },
    handleExceed() {
      // this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove() {
      // return this.$confirm(`确定移除 ${file.name}？`);
    },
  },
};
</script>

<style lang="scss" scoped>
body,
html {
  padding: 0;
  margin: 0;
}

.back {
  background: #c5c5c6;
}

.keyword {
  width: 327px;
  height: 100%;
  background: #ffffff;
  border-radius: 0px 0px 0px 0px;
}
.main {
  width: 100%;
  height: 94.8vh;
  padding: 0;
  margin: 0;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;

  
  // 左边
  .left {
    width: 30%;
    height: 95vh;
    // background-color: #e5e5e5;
    // text-align: center;
    // padding-top: 10px;
    box-sizing: border-box;
    overflow-y: scroll;

    // display: none;
    // padding: 10px;
    .content {
      width: 100%;
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      // border: 1px solid red;
      padding: 15px 20px;
      border-bottom: 1px solid black;
      font-size: 18px;
      overflow: hidden;

      .rights_button {
        max-width: 100%;
        // min-width: 50%;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }

      .imgs {
        width: 60px;
        height: 60px;
      }
    }

    .content-left {
      max-width: 75%;
      display: flex;
      // align-items: center;
    }

    .lefts {
      margin-right: 30px;
    }

    .rights {
      max-width: 80%;

      div {
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
    }

    .content-right {
      text-align: center;
      max-width: 25%;

      view {
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }

      .city {
        color: #ccc;
      }
    }
  }

  // 右边
  .right {
    width: 70%;
    height: 64vh;
    background-color: #f5f5f5;
    padding-top: 10px;
    box-sizing: border-box;
    overflow-y: scroll;

    // 聊天框
    .chat-content {
      width: 100%;
      height: 100vh;
      padding: 20px;

      // overflow-y:scroll
      .word {
        display: flex;
        margin-bottom: 20px;

        img {
          width: 40px;
          height: 40px;
          border-radius: 50%;
        }

        .info {
          margin-left: 10px;
          max-width: 90%;

          .time {
            font-size: 12px;
            color: rgba(51, 51, 51, 0.8);
            margin: 0;
            height: 20px;
            line-height: 20px;
            margin-top: -5px;
          }

          .info-content {
            max-width: 100%;
            padding: 10px;
            font-size: 18px;
            background: #fff;
            position: relative;
            margin-top: 8px;
            word-break: break-all;
          }

          // 小三角形
          .info-content::before {
            max-width: 70% !important;
            position: absolute;
            left: -8px;
            top: 8px;
            content: "";
            border-right: 10px solid #fff;
            border-top: 8px solid transparent;
            border-bottom: 8px solid transparent;
          }
        }
      }

      .word-my {
        display: flex;
        justify-content: flex-end;
        margin-bottom: 20px;

        img {
          width: 40px;
          height: 40px;
          border-radius: 50%;
        }

        .info {
          max-width: 90%;
          margin-left: 10px;
          text-align: right;

          .time {
            font-size: 12px;
            color: rgba(51, 51, 51, 0.8);
            margin: 0;
            height: 20px;
            line-height: 20px;
            margin-top: -5px;
            margin-right: 10px;
          }

          .info-content {
            // width: 90%;
            padding: 10px;
            font-size: 18px;
            float: right;
            margin-right: 10px;
            position: relative;
            margin-top: 8px;
            background: #a3c3f6;
            text-align: left;
            word-break: break-all;
          }

          //小三角形
          .info-content::after {
            position: absolute;
            right: -8px;
            top: 8px;
            content: "";
            border-left: 10px solid #a3c3f6;
            border-top: 8px solid transparent;
            border-bottom: 8px solid transparent;
          }
        }
      }
    }
  }
}

.chat {
  // display: none;
  width: 100%;
  height: 30%;
  border: 1px solid #a3c3f6;
  position: absolute;
  bottom: 5px;

  .chat_qq {
    border: none;
    outline: none;
    max-width: 70vw !important;
    // height: 100%;
    // text-align: left;
  }

  .clat_btn {
    width: 100%;
    height: 40px;
    line-height: 40px;
    position: relative;

    .del {
      position: absolute;
      top: 0px;
      right: 30%;
    }

    .del1 {
      position: absolute;
      top: 0px;
      right: 42%;
    }
  }
}
</style>
